package common

import (
	"errors"
	"io/ioutil"
	"net/http"
	"sync"
)

type Page struct {
	contentLength int64
	contentType   string
	charset       string
	content       *[]byte
	HttpResp      *http.Response
}

var bufferFree = sync.Pool{
	New: func() interface{} { return make([]byte, 10000) },
}

func newBuffer() []byte {
	buffer := bufferFree.Get().([]byte)
	return buffer
}

//func (self *Page) Selector() *goquery.Document {
//	doc, err := goquery.NewDocumentFromReader(strings.NewReader(self.Text()))
//	if err != nil {
//		logger.Error("%s", err)
//		return nil
//	}
//	return doc
//}
func (self *Page) Content() (content []byte, err error) {
	if self.content != nil {
		return *self.content, nil
	}
	if self.HttpResp == nil {
		return content, errors.New("http response is nil")
	}
	var bufferContent = newBuffer()
	bufferContent, err = ioutil.ReadAll(self.HttpResp.Body)
	if err != nil {
		return content, err
	}
	defer self.HttpResp.Body.Close()
	content = bufferContent
	self.content = &content
	return
}
func (self *Page) String() (string, error) {
	content, err := self.Content()
	if err != nil {
		return "", err
	}
	return string(content), nil
}

//func (self *Page) Text() string {
//	if strings.ToUpper(self.Charset()) == "UTF-8" {
//		return self.String()
//	}
//	charset := self.Charset()
//	return mahonia.NewDecoder(charset).ConvertString(self.String())
//}
